// ==UserScript==
// @name		eToolkit
// @version		0.0.2
// @description		eRepublik Toolkit
// @author		eToolkit
// @namespace		eToolkit
// @include		http://*.erepublik.com/*
// @include		http://erepublik.com/*
// @require		http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// @require		http://walakymas.comuv.com/gm/base.js
// ==/UserScript==

var TICKET = 'Moving Ticket';
var WEAPON = 'Weapon';
var FOOD   = 'Food';
var GIFT   = 'Gift';
var HOUSE  = 'House';
//
var WOOD   = 'Wood';
var GRAIN  = 'Grain';
var IRON   = 'Iron';
var OIL    = 'Oil';
var DIAMONDS = 'Diamonds';

var itemList = [FOOD, GIFT, WEAPON, TICKET, HOUSE, GRAIN, DIAMONDS, IRON, OIL, WOOD ]; 
var rawList = [WOOD, GRAIN, IRON, OIL, DIAMONDS];
var industries = {'gift':DIAMONDS,'weapon':IRON,'house':WOOD,'hospital':WOOD,'food':GRAIN,'movingticket':OIL, 'defense system':WOOD};


var BASE_URL = 'http://www.erepublik.com/';
var LANG = 'en';
var isCompany = false;
var isCitizen = false;
var companyType = null;
var companyID = 0;
var LOCATION = "";
var cID = 0;

function isRaw(type) {
	for(var key in rawList) {
		if (rawList[key]==type) {
			return true;
		}
	}
	return false;
}

function addGlobalStyle(css) {
	var head, style;
	head = document.getElementsByTagName('head')[0];
	if (!head) { return; }
	style = document.createElement('style');
	style.type = 'text/css';
	style.innerHTML = css;
	head.appendChild(style);
}


// BATTLEWATCH START //

var bw_contenttext ="";
var walls = new Array();
var prevwalls = new Array();
var oldbi;
var lastrefresh ="";
var timer_is_on; 
var change = new Array();  

function bw_on(){
    GM_setValue("battlewatch","1");
    getBattles();
    lastrefresh="";

}
function bw_off(){
    GM_setValue("battlewatch","0");
    regenerateContent();
    clearTimeout(t);
    lastrefresh="";
    timer_is_on=0;
}

function getVal(){
    runthis = GM_getValue("battlewatch","1");
    eadslink = GM_getValue("eadslink"); 
}

function getActualWall(bid){
    GM_xmlhttpRequest({
        method: "GET",
        url: "http://www.erepublik.com/en/battles/log/"+bid+"?how_many=1",
        onload: function(resp){
            var actual = eval('('+resp.responseText+')');
            if(actual["current_dp"] != 'undefined' && actual["current_dp"] != null){
                walls[bid] = actual["current_dp"];
            }else{
                walls[bid] = "0000";
            }
        }
    }); 
}

function getBattles() {
    
    if(!timer_is_on){
        createtimer();
    }
    time = new Date();
    battleinfo = oldbi;
    bw_contenttext = "<br><b>Active battles:</b><br>";
    if(lastrefresh+600000 < time.getTime()){
        GM_xmlhttpRequest({
            method: "GET",
            url: "http://erepmarket.co.cc/temp/getbattles.php",
            onload: function(response) { 
                lastrefresh = time.getTime();         
                var battleinfo = eval('('+response.responseText+')');
                oldbi = battleinfo;
                for(i in battleinfo){
                    var elem = battleinfo[i];
                    var bid = elem[0];
                    var aperma = elem[1];
                    var dperma = elem[2];
                    var wall = elem[3];
                    
                    getActualWall(bid);
                    
                    if(walls[bid] == "undefined" || walls[bid] == null){
                        awall = "waiting";
                    }else{
                        awall = walls[bid];
                    }
                    
                    if(aperma == dperma){
                        battlelink = "Resistance War "+'<img src="http://www.erepublik.com/images/flags/M/'+aperma+'.gif">';
                    }else{
                        battlelink = '<img src="http://www.erepublik.com/images/flags/M/'+aperma+'.gif">'+
                    ' vs. <img src="http://www.erepublik.com/images/flags/M/'+dperma+'.gif">';
                    }
                    
                    if(prevwalls[bid] == null){
                        prevwalls[bid] = 0;
                    }
                   
                    if(awall > parseFloat(prevwalls[bid])){
                        change[bid] = '<img src="http://erepmarket.co.cc/up.gif">';
                    }else if(awall < parseFloat(prevwalls[bid])) {
                        change[bid] = '<img src="http://erepmarket.co.cc/down.gif">';  
                    }else{
                        change[bid] = change[bid];
                    } 
                    if(change[bid] == null){
                        change[bid] = " ";
                    }
                    bw_contenttext += '<table border="0" cellspacing="0" cellpadding="0" style="border: 1px solid black;" width="120"><a href="http://www.erepublik.com/en/battles/show/'+bid+
                    '" target="_blank">'+battlelink+'</a><br>in '+elem[4]+'<br><img src="http://erepmarket.co.cc/wall.png" width="18" height="14"> '+awall+'/'+wall+' '+change[bid]+'</table><br>';
                    
                    battlelink="";
                    awall="";
                    
                    prevwalls[bid] = parseFloat(walls[bid]);
                }    
                
                regenerateContent();
            }


        });
    }else{
        for(i in battleinfo){
                    var elem = battleinfo[i];
                    var bid = elem[0];
                    var aperma = elem[1];
                    var dperma = elem[2];
                    var wall = elem[3];
                    
                    getActualWall(bid);
                    
                    if(walls[bid] == "undefined" || walls[bid] == null){
                        awall = "waiting...";
                    }else{
                        awall = walls[bid];
                    }
                    
                    if(aperma == dperma){
                        battlelink = "Resistance War "+'<img src="http://www.erepublik.com/images/flags/M/'+aperma+'.gif">';
                    }else{
                        battlelink = '<img src="http://www.erepublik.com/images/flags/M/'+aperma+'.gif">'+
                    ' vs. <img src="http://www.erepublik.com/images/flags/M/'+dperma+'.gif">';
                    }
                    
                    if(prevwalls[bid] == null){
                        prevwalls[bid] = 0;
                    }
                    
                  
                    if(awall > parseFloat(prevwalls[bid])){
                        change[bid] = '<img src="http://erepmarket.co.cc/up.gif">';
                    }else if(awall < parseFloat(prevwalls[bid])) {
                        change[bid] = '<img src="http://erepmarket.co.cc/down.gif">';  
                    }else{
                        change[bid] = change[bid];
                    } 
                    if(change[bid] == null){
                        change[bid] = " ";
                    }
                    
                    bw_contenttext += '<table border="0" cellspacing="0" cellpadding="0" style="border: 1px solid black;" width="120"><a href="http://www.erepublik.com/en/battles/show/'+bid+
                    '" target="_blank">'+battlelink+'</a><br>in '+elem[4]+'<br><img src="http://erepmarket.co.cc/wall.png" width="18" height="14"> '+awall+'/'+wall+' '+change[bid]+'</table><br>';
                    
                    battlelink="";
                    awall="";
                    
                    prevwalls[bid] = parseFloat(walls[bid]);
                }    
                
                regenerateContent();
    
    
    
    }
}



function regenerateContent(){
    getVal();
    
    if(runthis == 1){
         
        eads = document.getElementById("eads");
        if (eads){
            GM_setValue("eadslink", eads.src);
            document.getElementById("promo").removeChild(eads);
        }
        bw_content = document.getElementById("bw_content");
        if(bw_content == null){
            latest = document.getElementById("bw_buttons");
            bw_content = document.createElement("div");
            bw_content.innerHTML = bw_contenttext;
            bw_content.id = "bw_content";
            bw_content.style.textAlign = "center";
            latest.parentNode.appendChild(bw_content);
        }else{
            bw_content.innerHTML = bw_contenttext;
        }
    }else{
        bw_content = document.getElementById("bw_content");
        if(bw_content){
            document.getElementById("promo").removeChild(bw_content);
            latest = document.getElementById("bw_buttons");
            if(eadslink != null || eadslink != 'undefined'){
                eads = document.createElement("iframe");
                eads.src = eadslink;
                eads.id = "eads";
                eads.width = "120";
                eads.height = "1000";
                eads.frameborder = 0;
                eads.scrolling = "no";
                eads.style.border = "0";
                latest.parentNode.appendChild(eads);
            }
        }
    }
}
function timerstart(){
    getBattles();
    t=setTimeout(timerstart,5000);
}
function createtimer(){
    getVal();
    if (!timer_is_on && runthis==1 ){
        timer_is_on=1;
        timerstart();
    }
}

function StartBattleWatch() {
	newcss ='a.f_red_small_bw {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll right -154px;color:#000;font-size:11px;font-weight:normal;height:20px;line-height:20px;}';
	newcss +='a.f_red_small_bw span {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll left -154px;color:#000;cursor:pointer;height:20px;line-height:20px;margin-right:15px;padding-left:15px;text-align:center;text-shadow:0 1px 0 #aaa;}';
	newcss += 'a.f_red_small_bw:hover {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll right -174px;color:#FFFFFF;}';
	newcss += 'a.f_red_small_bw:hover span {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll left -174px;color:#FFFFFF;}';
	addGlobalStyle(newcss);

	newcss ='a.f_blue_small_bw {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll right -98px;color:#000;font-size:11px;font-weight:normal;height:20px;line-height:20px;}';
	newcss +='a.f_blue_small_bw span {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll left -98px;color:#000;cursor:pointer;height:20px;line-height:20px;margin-right:15px;padding-left:15px;text-align:center;text-shadow:0 1px 0 #aaa;}';
	newcss += 'a.f_blue_small_bw:hover {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll right -98px;color:#FFFFFF;}';
	newcss += 'a.f_blue_small_bw:hover span {-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#FFFFFF url(/images/parts/fluids_map.jpg) no-repeat scroll left -98px;color:#FFFFFF;}';
	addGlobalStyle(newcss);

	latest = document.getElementById("eads");
	gombok = document.createElement("div");
	gombok.id = "bw_buttons";
	gombok.style.textAlign ="center";
	gombok.style.width="120px";
	gombok.align="center";
	gombok.innerHTML = '<span style="background-color: #68e; width: 120px; display: block; border: 0; padding: 0;"><a href="http://erepmarket.co.cc" target="_blank" style="color: white">battleWatch</a></span>'+
	'<a class="f_blue_small_bw" href="#" id="bw_on_btn"><span>On</span></a><a class="f_red_small_bw" href="#" id="bw_off_btn"><span>Off</span></a>';
	latest.parentNode.insertBefore(gombok, latest);

	document.getElementById("bw_on_btn").addEventListener('click',bw_on, false);
	document.getElementById("bw_off_btn").addEventListener('click', bw_off, false);
	createtimer();
}
// BATTLEWATCH START //

// DONATER START //

function getButton(num) {
	return '<span style="font-size: 12px; font-weight: bold; border: 1px solid darkgrey;\
 padding: 5px 10px; cursor: pointer" class="rightpadded padded" id="add_'+num+'">Add '+num+'</span>';
}

function getDonateButton() {
	return '<span style="font-size: 12px; font-weight: bold; border: 1px solid darkgrey;\
 padding: 5px 10px; cursor: pointer" class="rightpadded padded" id="specDonate">Donate</span>';
}
function getType(html) {
		var type = 'U';
		if (html.indexOf('_industry_movingtickets.gif')>0) {
			type = TICKET;
		} else if (html.indexOf('_industry_weapon.gif')>0) {
			type = WEAPON;
		} else if (html.indexOf('_industry_food.gif')>0) {
			type = FOOD;
		} else if (html.indexOf('_industry_gift.gif')>0) {
			type = GIFT;
		} else if (html.indexOf('_industry_house.gif')>0) {
			type = HOUSE;
		} else if (html.indexOf('_industry_wood.gif')>0) {
			type = WOOD;
		} else if (html.indexOf('_industry_grain.gif')>0) {
			type = GRAIN;
		} else if (html.indexOf('_industry_iron.gif')>0) {
			type = IRON;
		} else if (html.indexOf('_industry_oil.gif')>0) {
			type = OIL;
		} else if (html.indexOf('_industry_diamonds.gif')>0) {
			type = DIAMONDS;
		}
		return type;
}

function getQuality(html) {
		var quality = 'Q1';
		
		var isHouse = html.indexOf('_industry_house.gif')>0;
		if (html.indexOf('20%')>0) {
			quality = 'Q1';
		} else if (html.indexOf('40%')>0) {
			quality = 'Q2';
		} else if (html.indexOf('60%')>0) {
			quality = 'Q3';
		} else if (html.indexOf('80%')>0) {
			quality = 'Q4';
		} else if (html.indexOf('100%')>0) {
			quality = 'Q5';
		}
		return quality;
}

function getInventory() {
	var result = new Array();
	$("#small li").each(function (i) {
		var type = getType(this.innerHTML);
		var qArray;
		if (result[type]) {
			qArray = result[type];
		} else {
			qArray = new Array();
			result[type]=qArray;
		}
		var quality = getQuality(this.innerHTML)
		if (qArray[quality]) {
			qArray[quality] += 1;
		} else {
			qArray[quality] = 1;
		}
	}
	);
	return result;
}

function forbidden(key) {
	var gmkey = "forb"+cID+"_"+key;
	var forb = GM_getValue(gmkey);
	if (forb == null || forb == 'undefined') {
		forb = false;
	}
	return forb;
}

function selected(key) {
	var gmkey = "forb"+cID+"_"+key;
	var forb = GM_getValue(gmkey);
	if (forb == null || forb == 'undefined') {
		forb = false;
	}
	if (forb) {
		$('#sp'+key).removeClass('cbforfidden').addClass('cbenabled');
	} else {
		$('#sp'+key).addClass('cbforfidden').removeClass('cbenabled');
	}
	GM_setValue(gmkey,!forb);
}

function getKey(q, t) {
	return q+"_"+t.substring(0,2);
}

function filter(arr, raw) {
	$('#myInventory').html('<form><table id ="inventoryTable" class="inventoryTable" width="250" border="1"><tr style="font-weight:bold;"><th>Type</th><th width="20">Q1</th><th width="20">Q2</th><th width="20">Q3</th width="20"><th width="20">Q4</th><th width="20">Q5</th></tr></table></form>');
	var foundSome = false;
	var foundProper = false;
	for ( var key in itemList) {
		var elem = itemList[key];
		if (!arr[elem]) {
			continue;
		}
		foundSome = true;
		var trkey =  elem.substring(0,2);
		$('#inventoryTable').append('<tr id="tr'+trkey+'"><th>'+elem + "</th></tr>");
		if (raw!=null) {
			if ( raw==elem ) {
				foundProper = true;
			}  else {
				$('#tr'+trkey).css('background-color','blue');
			} 
		}
		if (isCitizen && isRaw(elem)) {
			$('#tr'+trkey).css('background-color','blue');
		}
		for(var i = 1; i<=5; i++) {
			if (arr[elem]['Q'+i]) {
				var key = getKey('Q'+i,elem);
				$('#tr'+trkey).append('<td><span id="sp'+key+'">'
					+arr[elem]['Q'+i]+ '</span></td>');
				$('#sp'+key).addClass(forbidden(key)?'cbforfidden':'cbenabled');
				$('#sp'+key).click(function() { selected(this.id.substring(2)) });
			} else {
				$('#tr'+trkey).append('<td>--</td>');
			}
		}
	}
	if (!foundSome) {
		$('#myInventory').html("<span style='color: red; font-weight: bold;'>Empty Inventory</span>");
	} else if (raw!=null && !foundProper) {
		$('#myInventory').html("<span style='color: red; font-weight: bold;'>Your Inventory donesn't contain "+raw+"</span>");
	}
}

function addSome(num) {
	var width = $('#big').css('width');
	if (width.indexOf('px')>0) {
		max= width.substring(0,width.indexOf('px'))/57;
	}
	max -= $('#big li').length;
	if (num>max) {
		num = max;
	}
	$("#small li").each(function (i) {
		if (num>0) {
			var type = getType(this.innerHTML);
			if ((!isCompany || companyType==type) && (!isCitizen || !isRaw(type))) { 
				var key = getKey(getQuality(this.innerHTML),type);
				if (!forbidden(key)) {
					num -= 1;
					$(this).appendTo("#big");
				}
			}
		}
	});
}

function StartDonater(){
	isCitizen = LOCATION.indexOf("citizen")==0;
	var info = $("#items1").css('display','none');
	$("ul.tabs").after('<br/><table width="100%"><tr><td align="center"><div id="myInventory"></div></td></tr><tr><td align="center"><div id="myButtons" style="vertical-align:middle; height:20px; padding-top:8px;"></div></td></tr></table>');
	var inventory = getInventory(); 
	filter(inventory);
	$("#myButtons").append(getButton(1)+getButton(2)+getButton(3)+getButton(4)+getButton(5)+getButton(10)+getDonateButton());
	$("#add_1").click(function() { addSome(1) });
	$("#add_2").click(function() { addSome(2) });
	$("#add_3").click(function() { addSome(3) });
	$("#add_4").click(function() { addSome(4) });
	$("#add_5").click(function() { addSome(5) });
	$("#add_10").click(function() { addSome(10) });
	$("#specDonate").click(function() { 
		$("input.vround-btn-core").click();
	});
	addGlobalStyle(
'.inventoryTable th {font-weight:bold;}\
.inventoryTable td {text-align:center;}\
.cbforfidden {color:red;text-align:center;}\
.cbenabled {color:green;text-align:center;}\
');

	if (LOCATION.indexOf("company")==0) {
		companyID = LOCATION.split('/')[1];
		GM_xmlhttpRequest({
			method: 'GET',
			url: "http://api.erepublik.com/v1/feeds/companies/"+companyID+".json",
			onload:function(responseDetails){
				var companyObject = eval('(' + responseDetails.responseText + ')');
				var cType = companyObject.industry;
					
				companyType = industries[cType];
				isCompany = companyType != null; 
				filter(inventory, companyType);
			}	
		});
	}

}

// DONATER END //

// GIFTER START //

function fullgift(id){
	jQuery.post(
	'/citizen/offergift/'+id,
	{
		_token: $("#_token").val(),
		id:     id
	},
		function (data, textStatus) {
			var pp = 1;
			if (data.donated.status == "false"){
				$("#messagealert").css('display','block');
				$("#messagealert").attr("class","invalidicon");
			}else if(data.donated.status == "true"){
				$("#messagealert").css('display','none').fadeIn('fast');
				$("#messagealert").css('display','block');
				$("#messagealert").attr("class","validicon success_message");
				fullgift(id);
			}else if(data.donated.status == "captcha"){
				document.location = data.donated.back_url;
				pp = 0;
			}
			
			$("#messagealert").children("p").html(data.donated.message);
		},
	"json"
	);
}

function StartFullGifter(){
	var targetID = LOCATION.split('/')[2];
	if ($("#owninv").size() == 0) {
		$('#user_menu').append('<li><a id="full_gifter" href="javascript:void(0)">Full Gifter</a></li>');
		$('#full_gifter').click(function () {fullgift(targetID) });
	}
}

// GIFTER END //
// ALLCOMMENT BEGIN //

allCommentNode = function (e) {
	changeAllComment();
};

function changeAllComment(){
	$("a[href$='/20'][href*='/article/']").each(function (i) {
		var href = $(this).attr("href");
		href = href.substr(0,href.length-3)+"/all";
		$(this).attr("href",href);
	});
};


function StartAllComment(){
	changeAllComment();
	document.addEventListener("DOMNodeInserted", allCommentNode, false);
}

// ALLCOMMENT END //

// MILITARY ADVISER BEGIN //

var RANKS = ['Private', 'Corporal', 'Sergeant', 'Lieutenant', 'Captain', 'Colonel', 'General', 'Field Marshal'];

function DamageCalculator() {
    GM_addStyle('ul.weaponsel {-moz-background-clip:border; -moz-background-inline-policy:continuous;\
-moz-background-origin:padding; background:#FFFFFF none repeat scroll 0 0; border:1px solid #D1E8EF;\
display:block; float:left; margin-bottom:1px; margin-right:1px; overflow:hidden; } ');
    GM_addStyle('ul.weaponsel li { -moz-background-clip:border; -moz-background-inline-policy:continuous; -moz-background-origin:padding; \
background:#FFFFFF none repeat scroll 0 0; border:1px solid #D1E8EF; display:block; float:left; height:16px; margin-bottom:0px;\
overflow:hidden; width:15px; text-align:center;}');
GM_addStyle('input.weaponcount {width: 15px; padding-left: 5px; margin-left: 11px;}');
  
    //bal oldal
    var dt = '<tr><td valign="middle" nowrap="nowrap">'; 
    dt += '<table id="dcselect"><thead>Damage Calculator (Select Weapons)</thead><tbody>';
    for (i = 5; i >= 0; i--) {
        dt += '<tr><td style="border-bottom: 0px none; padding: 1px 15px 1px 72px;">'

        if (i>0)
            dt+= '<a onclick="location.href = this.href;" style="background-color: red" alt="Weapon Quality Level ' + i + '" title="Weapon Quality Level ' + i + '" href="/' + LOCALE + 'market/country-0-industry-3-quality-' + i + '">';
        else
            dt += '<a alt="Empty handed" title="Empty handed" href="/' + LOCALE + 'market/country-0-industry-3-quality-0">'

        dt += '<span class="qlsmallmeter" style="float: left; height: 15px; line-height: 15px; vertical-align: middle; margin-right: 14px">';
        dt += '<span class="qlsmalllevel" style="width: ' + (i * 2) + '0%">';
        dt += '<img style="padding-bottom: 1px" src="/images/parts/qlsmall-indicator_full.gif" />';
        dt += '</span></span></a>  <ul id="WQul'+i+'" class="weaponsel">';
        for (j = 0; j <= 5 ; j++)
            dt += '<li id="wpli'+i+'C'+j+'" class="weaponselem" style="-moz-user-select: none;">'+j+'</li>';
        dt += '</ul><input id="iweapon'+i+'" class="weaponcount" type="text" value="0" maxlength="2"></td><td id="wpdm'+i+'" align="left" style="padding: 0px; border-bottom:0px none;"> </td></tr>'; 
    }

    dt += '<tr><td style="border-bottom: 0px none; padding: 1px 10px 1px 180px;">Total Damage</td><td id="dcres" style="border-bottom: 0px none; padding: 0px 0px 0px 0px;"></td></tr></tbody></table>';
    dt += '</td><td id="calcDmg" width="166px" valign="middle"><span>&nbsp;</span></td></tr>'
    $('.offers tbody tr:first').next().next().after( dt );

    $('.weaponsel li:nth-child(1)').css('background' , '#AAD85B');
    $('.weaponsel li').live("click",function () {
        var weaponindex = $(this).attr('id')[4];
        var weaponcount = $(this).attr('id')[6];
        var iinput = $('#iweapon'+ weaponindex);
        if (iinput.val() == weaponcount){
            $('#wpli'+weaponindex+'C'+iinput.val()).css('background','#FFFFFF'); 
            iinput.val(0);
            $('#wpli'+weaponindex+'C'+iinput.val()).css('background','#AAD85B'); 
            }
        else {
            $('#wpli'+weaponindex+'C'+iinput.val()).css('background','#FFFFFF'); 
            iinput.val(weaponcount);
            $(this).css('background','#AAD85B');
        }
        calcDmg();
    });
    $('.weaponcount').live("change",function () {
        var weaponcount = $(this).val();
        var weaponindex = $(this).attr('id')[7];
        for(i=0;i<=5; i++){
            if (i==weaponcount)
                $('#wpli'+weaponindex+'C'+weaponcount).css('background','#AAD85B');
            else
                $('#wpli'+weaponindex+'C'+i).css('background','#FFFFFF');
        }
        calcDmg();
        });
    $('.weaponcount').live("keypress", function (event) {
        var e = event.which; var noStart = 48; var noEnd = 59; var jokerKey = 0;
        if ( e == 8 || e == 9 || e == 37 || e == 39 || ( noStart <= e && e < noEnd ) || jokerKey == e) return true;
    	else return false;
        });
}

function calcDmg() {
    var cWellness = parseFloat($('#wellnessvalue').text());
  	var strenght = parseFloat($("#content table td:eq(1)").text());
	var rankBonus = (RANKS.indexOf($("#content table td:eq(3) img").attr("alt")) + 1) * 0.2 + 1;
	var ConstDamage = 2 *  strenght * rankBonus;
    var totalDamage = 0;
    for(var i=5; i>=0; i--)
    {
       var db = $('#iweapon'+i).val();
       var qdam = ' [';
       var qtdmg = 0;
       for(j=0; j<db; j++) {
           if (cWellness >= 40)
           {
                var ctDamage = ConstDamage * (1 + (cWellness - 25) / 100);
                if (i>0) 
                    ctDamage = Math.ceil(ctDamage * (1+i/5));
                else    
                    ctDamage = Math.ceil(ctDamage * (1/2));

                cWellness -= 10;
                totalDamage += ctDamage;
                qtdmg += ctDamage;
                if (qdam.length<16){ 
                    if (j < 5 ) qdam += ctDamage;
                    if (qdam.length>14 && j<db-1) qdam += '..';
                    else if (j<db-1 && cWellness>=40) qdam +=' ';
                }
            }         
        }
        qdam += ']'
        if (db <2 || qtdmg == 0) qdam = ' ';
        if (db >0) $('#wpdm'+i).html('<strong>'+qtdmg+'</strong>'+qdam);
        else $('#wpdm'+i).html(' ');
   }
   $('#dcres').html('<strong>'+totalDamage+'</strong>');
}

function addGlobalStyle(css) {
	var head, style;
	head = document.getElementsByTagName('head')[0];
	if (!head) { return; }
	style = document.createElement('style');
	style.type = 'text/css';
	style.innerHTML = css;
	head.appendChild(style);
}

function GetErepDay() { 
 	var date = 0;
    date = parseInt($("#clock .eday strong").text() ,10);
	return date;
}

function damageSort(a, b) { return (b.day - a.day);}

function DamageUpdate() {
	var sReq = "http://api.erepublik.com/v1/feeds/citizens/";
	GM_log('DamageUpdate'+cID);
	GM_xmlhttpRequest({
		method: 'GET',
		url: sReq + cID + '.json',
		onload: function (json) {
			eval('prof = '+ json.responseText);
            var today = GetErepDay();
            GM_setValue('ma_savedday'+cID, today);

            var lastdamages = eval(GM_getValue('ma_zerodamages'+cID,undefined));
            if (lastdamages == undefined)
            {
                lastdamages = [{day: today, dam:(prof["damage"])}];
            }
            else
            {
                lastdamages.push({day: today, dam:(prof["damage"])});
                lastdamages.sort(damageSort);                
                while (lastdamages.length > 6)
                    lastdamages.pop();
            }                 
            GM_setValue('ma_zerodamages'+cID, uneval(lastdamages));
            
            if ($("#owninv").size() != 0)
                ProfileUpdate();
		},
	});
}

function ProfileUpdate () {
    var zdmg = eval(GM_getValue('ma_zerodamages'+cID));
    if (zdmg != undefined){
        var current = zdmg[0].dam;
        $('span.goright.special').each(function(i) {//p.padded 
            if ($(this).text().indexOf('/') != -1)
                current = parseInt($(this).text(),10);
        });
        var deltadm = current-zdmg[0].dam;
        var todaydm = '<p class="padded"><span class="goleft"><img class="iconsoft" src="/images/parts/icon-hero.gif" alt="Hero Fights"/>  Today Damage:</span>';
        todaydm += '<span class="goright special">&nbsp;&nbsp;&nbsp;'+deltadm+'&nbsp;</span>';
        
            todaydm += '<p class="padded"><span class="goleft"><img class="iconsoft" src="/images/parts/icon-hero.gif" alt="Hero Fights"/>  Latest Damages:</span>';
            for(var i=1; i<zdmg.length;i++)
            {
                todaydm += '<span class="goright special">'+zdmg[i].day+'&nbsp;Day:&nbsp;'+(zdmg[i-1].dam-zdmg[i].dam)+'&nbsp;</span>';//
            }
        
        $('div.quarter:last-child').append(todaydm);//div.holder.iep
    }
}

function BattleUpdate() {
    var today = GetErepDay();
    var inHTML = '<span class="double">Damages <br/>';//<div class="ls-half last">
    var damage = parseInt($('.lsvalue span').text(), 10);
    var ctotaldamage = ($('em.double:has(img[alt=Trivia-arrow-up])').text().match(/(\d+).\/.\d/)[1]);
    var lsdamage = eval(GM_getValue('lsdamage', undefined));  //[{ day: 650, dmg: [12340, 12367, 12410]}];  
    if (lsdamage == undefined) {
        lsdamage = [{ day: today, dmg: [(ctotaldamage - damage), ctotaldamage]}];
    }
    else {
        if (lsdamage[0].day != today) {
            lsdamage.push({ day: today, dmg: [(ctotaldamage - damage), ctotaldamage] })
     } else {
        lsdamage[0].dmg.push(ctotaldamage);
     }

     lsdamage.sort(damageSort);
     while (lsdamage.length > 6)
         lsdamage.pop();
    }
    
    GM_setValue('ma_lsdamage'+cID, uneval(lsdamage));

    var sum = 0;
    for (var i = 1; i < lsdamage[0].dmg.length; i++) {
        inHTML += (lsdamage[0].dmg[i] - lsdamage[0].dmg[i - 1]) + ' ';
        sum += (lsdamage[0].dmg[i] - lsdamage[0].dmg[i - 1]);
    }
    
    inHTML += '</span><em><span><strong>' + sum +' </strong></span></em>';
    $('.ls-half:eq(7)').html(inHTML);
}

var profileupdelayed = false;

function StartDamageCalculator() {
	DamageCalculator();
}

function StartProfileUpdate() {
	if (!profileupdelayed && $("#owninv").size() != 0) {
		ProfileUpdate();
	}
}

function StartBattleUpdate() {
	BattleUpdate();
}

// MILITARY ADVISER END //


function enabled(order) {
	return true;
}

function Main(e) {
	var HREF = location.href;
	if (HREF.indexOf("http://")==0 || HREF.indexOf("https://")==0) {
		var parts = HREF.split('/');
		BASE_URL = parts[0]+'//'+parts[2]+'/';
		LANG = parts[3];
	}

	try {
		cID = $("div.core div.avatarholder a").attr("href").split('/')[4];
	} catch (e) {
		GM_log('cID:'+$("div.core div.avatarholder a").attr("href")+","+e);
	}
	
	if (GetErepDay() != GM_getValue('ma_savedday'+cID, 0))
	{
	        profileupdelayed = true;
	        DamageUpdate();
	}

	var pagesFunctions = [
		{p: 'citizen/profile', 	s:1, 	f: StartFullGifter},
		{p: 'donate/items',	s:2, 	f: StartDonater},
		{p: 'all',		s:3, 	f: StartBattleWatch},
		{p: 'all',		s:4, 	f: StartAllComment},
		{p: 'my-places/army',	s:5, 	f: StartDamageCalculator},
		{p: 'citizen/profile',	s:5, 	f: StartProfileUpdate},
		{p: 'battles/fight',	s:5, 	f: StartBattleUpdate},
	];
	
	if (HREF.indexOf(BASE_URL)==0) {
		LOCATION = HREF.substring(BASE_URL.length+3);
		pagesFunctions.forEach(function(v) {
//			if ((LOCATION.indexOf(v.p)>0) && (getSetting(v.s) != '0' || v.s == '-1'))
//				v.f();
			if ((v.p=="all" || LOCATION.indexOf(v.p)>=0) && enabled(v.s)) v.f();
		});
	}
}
	
var $ = jQuery.noConflict();
window.addEventListener('load', Main, false);
